//
//  RequestErrorHandle.swift
//  Demo
//
//  Created by susu on 2020/12/18.
//

import Foundation
import PanKit
import MXCommonModule

struct XGL_CustomRequestError: PanRequestError {

    struct ErrorCode {
        static let TokenError = "10023"
        static let NetworkError = "6"
        static let TimeOut = "0x999"
    }
    
    enum XGL_CustomRequestErrorEnum {
        case NomalError(errorMessage: String?)
        case TokenError(errorMessage: String?)
    }
    
    var errorCode: String = ""
    var errorMessage: String = ""
    
    var errorType: XGL_CustomRequestErrorEnum = .NomalError(errorMessage: "Network request failed"){
        didSet{
            self.handleRequestError()
        }
    }
    
    init(errorCode: String, errorMessage: String, other: String?) {
        self.errorCode = errorCode
        self.errorMessage = errorMessage
        if errorCode == ErrorCode.TokenError{
            self.errorType = .TokenError(errorMessage: errorMessage)
        }else if errorCode == ErrorCode.NetworkError{
            self.errorType = .NomalError(errorMessage: "Network connection failed, please check your network connection")
        }else{
            self.errorType = .NomalError(errorMessage: errorMessage)
        }
        self.handleRequestError()
    }
    
    private func handleRequestError(){
        guard let window = UIApplication.shared.currentWindow,let controller = window.visibleViewController()else {
            return
        }
        switch self.errorType {
        case .NomalError(let errorMessage):
            if let message = errorMessage {
                debugPrint(message)
                MXProgressHUD.hudWithText(message)
            }else{
//                MXProgressHUD.hudWithText("Network connection failed, please check your network connection")
            }
            break
        case .TokenError(_):
            if !controller.isKind(of: LoginViewController.self){
                let alert = UIAlertController(title: "Tips", message: "Your login information has expired, please login again", preferredStyle: .alert)
                let action = UIAlertAction(title: "Sure", style: .default) { (action) in
                    XGL_Notice.default.post(name: XGL_Notification.tokenOverdue.notificationName, object: nil)
                    controller.present(loginNaviController, animated: true, completion: nil)
                }
                alert.addAction(action)
                controller.navigationController?.popToRootViewController(animated: false)
                if controller.presentingViewController == nil{
                    controller.present(alert, animated: true, completion: nil)
                }
            }
            break
        }
    }
}

